<template>
  <div class="notice-management">
    <div class="header">
      <h2>企业公告管理</h2>
      <el-button type="primary" @click="showAddDialog" v-if="hasPermission(['档案管理员', '企业领导'])">
        发布公告
      </el-button>
    </div>

    <!-- 公告列表 -->
    <el-table :data="notices" style="width: 100%" v-loading="loading">
      <el-table-column prop="title" label="标题" width="200"></el-table-column>
      <el-table-column prop="content" label="内容" show-overflow-tooltip></el-table-column>
      <el-table-column prop="publisherName" label="发布人" width="120"></el-table-column>
      <el-table-column prop="publishTime" label="发布时间" width="180">
        <template slot-scope="scope">
          {{ formatDate(scope.row.publishTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template slot-scope="scope">
          <el-button size="mini" @click="viewNotice(scope.row)">查看详情</el-button>
          <el-button size="mini" type="primary" @click="approveNotice(scope.row)" 
                     v-if="userRole === '企业领导' && scope.row.status === 'draft'">
            审核通过
          </el-button>
          <el-button size="mini" type="warning" @click="rejectNotice(scope.row)" 
                     v-if="userRole === '企业领导' && scope.row.status === 'draft'">
            驳回
          </el-button>
          <el-button size="mini" type="danger" @click="deleteNotice(scope.row.noticeId)"
                     v-if="canDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      layout="total, prev, pager, next">
    </el-pagination>

    <!-- 发布公告对话框 -->
    <el-dialog title="发布公告" :visible.sync="addDialogVisible" width="600px">
      <el-form :model="noticeForm" :rules="noticeRules" ref="noticeForm">
        <el-form-item label="标题" prop="title">
          <el-input v-model="noticeForm.title"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input type="textarea" :rows="8" v-model="noticeForm.content"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="publishNotice">发布</el-button>
      </div>
    </el-dialog>

    <!-- 查看公告对话框 -->
    <el-dialog title="公告详情" :visible.sync="viewDialogVisible" width="600px">
      <div v-if="currentNotice">
        <h3>{{ currentNotice.title }}</h3>
        <p><strong>发布人：</strong>{{ currentNotice.publisherName }}</p>
        <p><strong>发布时间：</strong>{{ formatDate(currentNotice.publishTime) }}</p>
        <div class="content">
          <strong>内容：</strong>
          <div v-html="currentNotice.content"></div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import service from '@/utils/request'

export default {
  name: 'NoticeManagement',
  data() {
    return {
      notices: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      userRole: '',
      userId: 0,
      addDialogVisible: false,
      viewDialogVisible: false,
      currentNotice: null,
      noticeForm: {
        title: '',
        content: '',
        publisherId: 0
      },
      noticeRules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 从localStorage中获取用户信息
    const user = JSON.parse(localStorage.getItem('user') || '{}');
    this.userRole = user.role || '';
    this.userId = user.userId || 0;
    console.log('初始化用户角色:', this.userRole);
    console.log('初始化用户ID:', this.userId);
  },
  mounted() {
    this.loadNotices()
  },
  methods: {
    hasPermission(roles) {
      console.log('当前用户角色:', this.userRole);
      console.log('检查权限:', roles);
      return roles.includes(this.userRole);
    },
    
    canDelete(notice) {
      // 企业领导可以删除任何公告，档案管理员只能删除自己发布的草稿
      if (this.userRole === '企业领导') {
        return true;
      }
      if (this.userRole === '档案管理员') {
        return notice.publisherId === this.userId && notice.status === 'draft';
      }
      return false;
    },

    async loadNotices() {
      this.loading = true
      try {
        let url;
        if (this.userRole === '普通员工') {
          // 普通员工只能看到已发布的公告
          url = '/api/notices/published';
        } else {
          // 管理员和领导可以看到所有公告
          url = `/api/notices/page?current=${this.currentPage}&size=${this.pageSize}`;
        }
        
        const response = await service.get(url)
        if (response.data.code === 200) {
          if (this.userRole === '普通员工') {
            this.notices = response.data.data
            this.total = response.data.data.length
          } else {
            this.notices = response.data.data.records
            this.total = response.data.data.total
          }
        }
      } catch (error) {
        this.$message.error('加载公告失败')
      }
      this.loading = false
    },
    
    showAddDialog() {
      this.addDialogVisible = true
      this.noticeForm = {
        title: '',
        content: '',
        publisherId: this.userId
      }
    },
    
    async publishNotice() {
      this.$refs.noticeForm.validate(async (valid) => {
        if (valid) {
          try {
            // 企业领导发布的公告直接发布，档案管理员发布的需要审核
            const status = this.userRole === '企业领导' ? 'published' : 'draft';
            const noticeData = {
              ...this.noticeForm,
              status: status
            };
            
            const response = await service.post('/api/notices/publish', noticeData)
            if (response.data.code === 200) {
              const message = status === 'published' ? '发布成功' : '提交成功，等待审核';
              this.$message.success(message)
              this.addDialogVisible = false
              this.loadNotices()
            } else {
              this.$message.error(response.data.message)
            }
          } catch (error) {
            this.$message.error('发布失败')
          }
        }
      })
    },
    
    viewNotice(notice) {
      this.currentNotice = notice
      this.viewDialogVisible = true
    },
    
    async approveNotice(notice) {
      try {
        const response = await service.put(`/api/notices/approve/${notice.noticeId}?status=published`)
        if (response.data.code === 200) {
          this.$message.success('审核通过')
          this.loadNotices()
        } else {
          this.$message.error(response.data.message)
        }
      } catch (error) {
        this.$message.error('审核失败')
      }
    },
    
    async rejectNotice(notice) {
      this.$confirm('确认驳回此公告？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await service.put(`/api/notices/approve/${notice.noticeId}?status=rejected`)
          if (response.data.code === 200) {
            this.$message.success('已驳回')
            this.loadNotices()
          } else {
            this.$message.error(response.data.message)
          }
        } catch (error) {
          this.$message.error('操作失败')
        }
      })
    },
    
    async deleteNotice(id) {
      this.$confirm('确认删除此公告？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await service.delete(`/api/notices/${id}`)
          if (response.data.code === 200) {
            this.$message.success('删除成功')
            this.loadNotices()
          } else {
            this.$message.error(response.data.message)
          }
        } catch (error) {
          this.$message.error('删除失败')
        }
      })
    },
    
    handleCurrentChange(page) {
      this.currentPage = page
      this.loadNotices()
    },
    
    formatDate(dateStr) {
      if (!dateStr) return ''
      return new Date(dateStr).toLocaleString()
    },
    
    getStatusType(status) {
      const typeMap = {
        'published': 'success',
        'draft': 'warning',
        'archived': 'info'
      }
      return typeMap[status] || 'info'
    },
    
    getStatusText(status) {
      const textMap = {
        'published': '已发布',
        'draft': '草稿',
        'archived': '已归档'
      }
      return textMap[status] || status
    }
  }
}
</script>

<style scoped>
.notice-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.content {
  margin-top: 15px;
  line-height: 1.6;
}

.el-pagination {
  margin-top: 20px;
  text-align: center;
}
</style> 